// stores/permission.ts
import { defineStore } from 'pinia'
import { getPermissions } from '@/api/role'

interface Permission {
  code: string
  name: string
  type: number
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    permissions: [] as Permission[]
  }),
  
  getters: {
    // 获取所有权限code数组
    permissionCodes: (state) => {
      return state.permissions.map(p => p.code)
    },
    
    // 获取按钮权限
    buttonPermissions: (state) => {
      return state.permissions.filter(p => p.type === 2)
    }
  },
  
  actions: {
    setPermissions(permissions: Permission[]) {
      this.permissions = permissions
    },
    
    hasPermission(code: string): boolean {
      return this.permissions.some(p => p.code === code)
    },
    
    // 从API获取权限
    async fetchPermissions(id: number) {
      try {
        const result = await getPermissions(id)
        //console.log('获取权限成功:', result)
                
        if (result.code === 200) {
          this.setPermissions(result.data)
          localStorage.setItem('menu', JSON.stringify(result.menu))
          return result.data
        } else {
          throw new Error(result.message)
        }
      } catch (error) {
        //console.error('获取权限失败:', error)
        throw error
      }
    }
  }
})